package com.cloud.gateway.controller.api;

import com.alibaba.fastjson.JSON;
import com.cloud.common.BaseReturn;
import com.cloud.common.JwtUtils;
import com.cloud.server.domain.user.SubjectType;
import com.cloud.server.domain.user.User;
import com.cloud.server.from.login.FromLoginUser;
import com.cloud.server.from.login.LoginUserData;
import com.cloud.server.service.user.LoginService;
import com.cloud.server.service.user.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

/**
 * @Author liuyuan
 * @Date 2021/11/23 8:38 上午
 * @Version 1.0
 */
@RequestMapping("/api")
@RestController
public class LoginController {

    @Autowired
    UserService userService;
    @Autowired
    ApplicationContext applicationContext;
    @Autowired
    StringRedisTemplate stringRedisTemplate;


    @RequestMapping("/login")
    public BaseReturn login(@RequestBody FromLoginUser fromLoginUser){
        LoginUserData loginUserData = new LoginUserData();
        LoginService loginService = (LoginService)applicationContext.getBean(fromLoginUser.getLoginType().getDesc());
        try {
            User user = loginService.login(fromLoginUser);
            BeanUtils.copyProperties(user,loginUserData);
            String token = JwtUtils.geneJsonWebToken(user.getId(), user.getRealName(), SubjectType.USER);
            stringRedisTemplate.opsForValue().set(token,String.valueOf(user.getId()),60 * 30, TimeUnit.SECONDS);
            loginUserData.setPassword(null);
            loginUserData.setAuthorization(token);
            return BaseReturn.build("200","登陆成功",loginUserData);
        } catch (Exception e) {
            e.printStackTrace();
            return BaseReturn.build("500",e.getMessage());
        }

    }



}
